﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Jurassic;

using Happy.Activities.Domain.WorkflowInstances;

namespace Happy.Activities.Domain.Workflows
{
    /// <summary>
    /// 脚本路由条件。
    /// </summary>
    public sealed class ScriptRouterCondition : IRouterCondition
    {
        private readonly string _serializedConditionContent;

        /// <summary>
        /// 构造方法。
        /// </summary>
        public ScriptRouterCondition(string serializedConditionContent)
        {
            _serializedConditionContent = serializedConditionContent;
        }

        /// <inheritdoc />
        public bool CanRoute(WorkflowContext context, ActivityInstance fromActivityInstance, Router router)
        {
            var engine = new ScriptEngine();

            foreach (var item in context.Agrs)
            {
                engine.SetGlobalValue(item.Key, item.Value);
            }

            return (bool)engine.Evaluate(_serializedConditionContent);
        }

        /// <inheritdoc />
        public string SerializedToString()
        {
            return _serializedConditionContent;
        }
    }
}
